package com.atguigu.flink.splitAndUnionStream;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class SplitStreamSideOutPut {

    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);

        SingleOutputStreamOperator<WaterSensor> mapDS = socketDS.map(new WaterSensorMapFunction());

        OutputTag<WaterSensor> ws1Tag = new OutputTag<WaterSensor>("ws1Tag" , Types.POJO(WaterSensor.class));
        OutputTag<WaterSensor> ws2Tag = new OutputTag<WaterSensor>("ws2Tag" , Types.POJO(WaterSensor.class));

        //如果使用测输出流，处理函数只能调用process 因为process 可以传递上下文
        SingleOutputStreamOperator<WaterSensor> splitDS = mapDS.process(
                new ProcessFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void processElement(WaterSensor ws, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                        String id = ws.getId();
                        if ("ws1".equals(id)) {
                            ctx.output(ws1Tag, ws);
                        } else if ("ws2".equals(id)) {
                            ctx.output(ws2Tag, ws);
                        } else {
                            out.collect(ws);
                        }
                    }
                }
        );

        splitDS.getSideOutput(ws1Tag).print();
        splitDS.getSideOutput(ws2Tag).print();
        splitDS.print();
    }
}
